package com.sunfeng.netty.atguigu2.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author sunfeng
 * @date 2021/03/23 09:33
 **/
public class NIOServer2 {
    public static void main(String[] args) throws IOException {

        // 创建ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //创建Selector
        Selector selector = Selector.open();
        //讲ServerSocketChannel 设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.bind(new InetSocketAddress(9999));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if (selector.select(1000) == 0) {

                System.out.println("暂无连接请求");
                continue;
            }
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();

            while (keyIterator.hasNext()){
                SelectionKey selectionKey = keyIterator.next();

                if(selectionKey.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("获得连接的ServerSocket的HashCode为:"+socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ);

                }
                if(selectionKey.isReadable()){
                    SocketChannel channel = (SocketChannel)selectionKey.channel();

                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    try {
                        int read = channel.read(byteBuffer);
                        if (read>0){
                            System.out.println("获取到的数据为："+new String(byteBuffer.array()));
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        channel.close();
                    }

                }
                keyIterator.remove();

            }

        }


    }
}
